<?php

namespace App\Models\Car;

use App\Models\Constant\CarConstant;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Models\Common\CommonModel;
class CarInfo extends CommonModel
{
    use HasFactory;

    protected $table = 'car_info';
    protected $appends = ['type_name','status_name'];

    public function getTypeNameAttribute(){
        return $this->type==1?'油车':'新能源';
    }
    public function getStatusNameAttribute(){
        return CarConstant::CarStatus[$this->status]??'未知';
    }

    public function getLst(array $conditions = []){
        $records = parent::getLst($conditions); // TODO: Change the autogenerated stub
        if(!empty($conditions['car_no'])){
            $records = $records->where('car_no','like','%'.$conditions['car_no'].'%');
        }
        if(!empty($conditions['brand'])){
            $records = $records->where('brand',$conditions['brand']);
        }
        if(!empty($conditions['insurance_date'])){
            $records = $records->whereBetween('insurance_date',[date('Y-m-d'),$conditions['insurance_date']]);
        }

        return $records;
    }

    public function getFreeCars(){
        return self::query()->where('status',CarConstant::CAR_STATUS_FREE)->get(['id','car_no']);
    }
    public function getAllCars(){
        return self::query()->get(['id','car_no']);
    }

    public function getRentUnit(){
        $unitName = '';
        if($this->status==CarConstant::CAR_STATUS_BUSY){
            $sql = "find_in_set(".$this->id.",car_ids)";
            $order = Order::query()->whereRaw($sql)->where('status',CarConstant::ORDER_STATUS_GOING)->first();
            if (!empty($order)) $unitName = $order->rent_unit_name;
        }
        return $unitName;
    }
}
